<template>
  <!-- 添加采购  -->
  <div class="contractInfo box">
    <el-card
      shadow="never"
      :header="titleMap[mode]"
      class="item-background"
      style="width: 100%"
    >
      <el-form
        :model="form"
        :rules="rules"
        ref="addForm"
        label-width="auto"
        label-position="right"
      >
        <el-form-item label="标题" prop="title" style="width: 100%">
          <el-input
            v-model="form.title"
            clearable
            placeholder="请输入标题"
          ></el-input>
        </el-form-item>
        <el-form-item label="供应商">
          <el-input
            v-model="form.vendorName"
            clearable
            @click="showSelectVendor"
            placeholder="请选择供应商"
          ></el-input>
        </el-form-item>
        <el-form-item label="采购部门" prop="procuredDepartmentId">
          <el-select
            v-model="form.procuredDepartmentId"
            placeholder="请选择"
            @change="selectDeaprtment"
            style="width: 100%"
          >
            <el-option
              v-for="item in departmentList"
              :key="item.id"
              :label="item.name"
              :value="item.id"
            />
          </el-select>
        </el-form-item>

        <el-form-item label="采购人" prop="procuredAdminId">
          <el-select
            v-model="form.procuredAdminId"
            placeholder="请选择"
            style="width: 100%"
          >
            <el-option
              v-for="item in userList"
              :key="item.id"
              :label="item.username"
              :value="item.id"
            />
          </el-select>
        </el-form-item>
        <el-form-item label="采购时间" prop="procuredTime">
          <el-date-picker
            v-model="form.procuredTime"
            type="date"
            placeholder="请选择采购时间"
            value-format="YYYY-MM-DD"
            style="width: 100%"
          >
          </el-date-picker>
        </el-form-item>
        <el-form-item label="到货时间" prop="arrivalTime">
          <el-date-picker
            v-model="form.arrivalTime"
            type="date"
            placeholder="请选择采购时间"
            value-format="YYYY-MM-DD"
            style="width: 100%"
          >
          </el-date-picker>
        </el-form-item>
        <el-form-item></el-form-item>
        <el-form-item
          label="采购物品"
          prop="warehouseId"
          request
          v-if="!$route.query.from"
        >
          <el-button type="primary" plain @click="showSelectGoods"
            >选择物品</el-button
          >
        </el-form-item>

        <el-form-item label="采购明细" prop="adminId" style="width: 100%">
          <el-table
            ref="table"
            :data="goodsList"
            placeholder="暂无数据"
            stripe
            border
            v-if="$route.query.from"
          >
            <!-- :showSummary="true" -->
            <el-table-column label="物品名称" prop="productName">
            </el-table-column>
            <el-table-column label="规格型号" prop="specificationName">
            </el-table-column>

            <el-table-column label="请购数量" prop="productBuyNum">
              <template #default="scope">
                <p>{{ scope.row.productBuyNum }}</p>
              </template>
            </el-table-column>
            <el-table-column label="采购单价(元)" prop="price">
              <template #default="scope">
                <el-input
                  v-model="scope.row.price"
                  clearable
                  oninput="value=value.replace(/^\D*([0-9]\d*\.?\d{0,2})?.*$/,'$1')"
                  @blur="scope.row.price = $event.target.value"
                ></el-input>
                <!-- <el-input-number
                  v-model="scope.row.price"
                  :min="0"
                ></el-input-number> -->
              </template>
            </el-table-column>
            <el-table-column label="仓库单位" prop="unitName">
            </el-table-column>
            <el-table-column label="采购数量" prop="financeBuyNum">
              <template #default="scope">
                <el-input
                  v-model="scope.row.financeBuyNum"
                  clearable
                  placeholder="请输入采购数量"
                  oninput="value=value.replace(/^\D*([0-9]\d*)?.*$/,'$1')"
                  @blur="scope.row.financeBuyNum = $event.target.value"
                ></el-input>
              </template>
            </el-table-column>
            <el-table-column label="采购单位" prop="financeUnitName">
            </el-table-column>
            <el-table-column
              label="总价格(元)"
              width="200"
              prop="productBuyPrice"
            >
            </el-table-column>
          </el-table>
          <sc-form-table
            ref="table"
            v-model="goodsList"
            placeholder="暂无数据"
            :hideAdd="true"
            stripe
            border
            v-else
          >
            <!-- :showSummary="true" -->
            <el-table-column label="物品名称" prop="productName">
            </el-table-column>
            <el-table-column label="规格型号" prop="specificationName">
            </el-table-column>
            <el-table-column label="采购单价(元)" prop="price">
              <template #default="scope">
                <el-input
                  v-model="scope.row.price"
                  clearable
                  oninput="value=value.replace(/^\D*([0-9]\d*\.?\d{0,2})?.*$/,'$1')"
                  @blur="scope.row.price = $event.target.value"
                ></el-input>
                <!-- <el-input-number v-model="scope.row.price"  :min="0"></el-input-number> -->
              </template>
            </el-table-column>
            <el-table-column label="采购数量" prop="financeBuyNum">
              <!-- isPurchase	是否从请购单来 1否 2是 -->
              <template #default="scope">
                <p v-if="scope.row.isPurchase">
                  {{ scope.row.financeBuyNum }}
                </p>
                <el-input
                  v-else
                  v-model="scope.row.financeBuyNum"
                  clearable
                  placeholder="请输入采购数量"
                  oninput="value=value.replace(/^\D*([0-9]\d*)?.*$/,'$1')"
                  @blur="scope.row.financeBuyNum = $event.target.value"
                ></el-input>
                <!-- <el-input-number v-else v-model="scope.row.financeBuyNum"  min="0"></el-input-number> -->
              </template>
            </el-table-column>
            <el-table-column label="采购单位" prop="unitName">
            </el-table-column>
          </sc-form-table>
        </el-form-item>
        <el-form-item label="备注" style="width: 100%">
          <el-input
            type="textarea"
            v-model="form.remark"
            rows="3"
            clearable
            placeholder="请输入备注"
          ></el-input>
        </el-form-item>
      </el-form>

      <!-- 审核流程项 -->
      <check-form-item
        ref="checkFormItem"
        @setCheckConfig="setCheckConfig"
        :field="this.form"
        :checkType="checkType"
        v-show="$route.query.mode == 'add'"
      ></check-form-item>

      <div class="button">
        <el-button type="primary" @click="save" :loading="isSaveing"
          >保 存</el-button
        >
        <el-button @click="cencel">取 消</el-button>
      </div>
    </el-card>

    <!-- 选择供应商 -->
    <select-vendor ref="selectVendor" @setVendor="setVendor"></select-vendor>

    <!-- 选择物品 -->
    <select-goods ref="selectGoods" @selectGoods="selectGoods"></select-goods>
  </div>
</template>
<script>
import selectUser from '@/components/selectUser'
import selectGoods from '../../components/selectGoods'
import selectVendor from '@/components/selectVendor'
import checkFormItem from '@/components/checkProcess/checkFormItem.vue'
export default {
  name: 'addPurchase',
  data () {
    return {
      checkType: 23,//工作流的类型
      mode: this.$route.query.mode,
      titleMap: {
        add: '添加',
        edit: '编辑',
      },
      isSaveing: false,
      attrObj: null,
      form: {
        adminId: '',
        departmentId: '',
        procuredDepartmentId: '',//部门id
        procuredAdminId: '',//采购人id
        vendorId: '',//供应商id
        vendorName: '',
        title: '',
        procuredTime: '',//	采购时间
        arrivalTime: '',//	到货时间
        purchaseIds: '',//请购单ids
        remark: '',//备注
        exempt: '',//是否免审
        procurementProductList: [],//采购物品list
        workflowJsonList: []
      },
      vendorList: [], //供应商列表  
      departmentList: [],//部门列表
      userList: [],//用户列表
      goodsList: [],//采购物品列表
      userInfo: {},
      rules: {
        title: [
          { required: true, message: '请输入标题', trigger: 'blur' }
        ],
        procuredDepartmentId: [
          { required: true, message: '请选择部门', trigger: 'change' }
        ],
        procuredAdminId: [
          { required: true, message: '请选择采购人', trigger: 'change' }
        ],
        procuredTime: [
          { type: 'date', required: true, message: '请选择采购时间', trigger: 'change' }
        ],
        arrivalTime: [
          { type: 'date', required: true, message: '请选择到货时间', trigger: 'change' }
        ]
      }
    }
  },
  components: {
    selectUser,
    selectGoods,
    selectVendor,
    checkFormItem

  },
  created () {
    if (this.$route.query.from == 'createOrder') {
      let data = this.$TOOL.data.get("ORDERDATA")
      this.goodsList = data.goodsList
      this.form.purchaseIds = data.ids
    }
  },
  mounted () {
    this.userInfo = this.$TOOL.data.get('USER_INFO')
    this.form.adminId = this.userInfo.userId
    this.form.departmentId = this.userInfo.departmentId
    if (this.$route.query.mode == 'edit') this.getDetail()
    this.getDepartmentList()
    this.getUserList()
  },
  methods: {
    // 审批流配置
    setCheckConfig (list, exempt) {
      this.form.workflowJsonList = list
      this.form.exempt = exempt
    },

    // 获取采购单详情
    async getDetail () {
      let param = {
        limit: 1000,
        page: 1,
        id: this.$route.query.id,
      }
      let { data } = await this.$API.purchase.getPurchaseList.get(param)
      this.form = data[0]
      this.goodsList = data[0].procurementProductList
      console.log(data)

    },

    // 获取部门
    async getDepartmentList () {
      let { data } = await this.$API.department.getDepartmentList.get()
      this.departmentList = data

    },

    // 获取用户列表
    async getUserList (id) {
      let param = {
        limit: 1000,
        page: 1,
        departmentId: id
      }
      let { data } = await this.$API.user.getUserList.get(param)
      this.userList = data
    },

    // 选择部门
    selectDeaprtment (id) {
      this.form.procuredAdminId = ' '
      this.getUserList(id)
    },

    // 显示物品选择列表
    showSelectGoods () {
      this.$refs.selectGoods.open()
    },

    // 请购物品列表
    selectGoods (list) {
      list.map(item => {
        item.productName = item.name
        item.specificationName = item.spuSpecification
        item.unitName = item.productUnitName
      })
      this.goodsList = [...this.goodsList, ...list]
      console.log(list)
    },

    showSelectVendor () {
      this.$refs.selectVendor.open()
    },

    setVendor (data) {
      console.log(data)
      this.form.vendorName = data.name
      this.form.vendorId = data.id
    },

    // 添加
    save () {
      this.$refs.addForm.validate(async (valid) => {
        if (valid) {
          if (this.goodsList.length == 0) {
            this.$message.error("请选择采购物品")
            return
          }
          let noNum = false
          let obj = null
          let list = []
          this.goodsList.map(item => {
            obj = {
              requisitionProductId: this.$route.query.from ? item.id : '',
              id: item.id,
              productSpuId: item.productSpuId,
              productBuyPrice: item.productBuyPrice,
              productBuyNum: item.productBuyNum,
              financeBuyNum: item.financeBuyNum,
              price: item.price,
              productName: item.productName,
              specificationName: item.specificationName,
              unitId: item.unitId,
              unitName: item.unitName,
              financeUnitName: item.financeUnitName
            }
            list.push(obj)
            if (obj.financeBuyNum == '') {
              noNum = true
              this.$message.error(`请输入${obj.productName}的数量`)
            }
          })
          this.form.procurementProductList = list
          if (noNum) return

          let res = null
          let mode = this.$route.query.mode
          this.isSaveing = true
          if (mode == 'add') {
            res = await this.$API.purchase.addPurchase.post(this.form)
            this.$TOOL.data.remove("ORDERDATA")
          } else if (mode == 'edit') {
            let data = {
              adminId: this.userInfo.userId,
              id: this.form.id,
              departmentId: this.form.departmentId,
              procuredDepartmentId: this.form.procuredDepartmentId,
              procuredAdminId: this.form.procuredAdminId,
              vendorId: this.form.vendorId,
              vendorName: this.form.vendorName,
              title: this.form.title,
              procuredTime: this.form.procuredTime,
              arrivalTime: this.form.arrivalTime,
              purchaseIds: this.form.purchaseIds,
              remark: this.form.remark,
              procurementProductList: this.form.procurementProductList,
              workflowJsonList: this.form.workflowJsonList
            }
            res = await this.$API.purchase.updatePurchase.post(data)
          }
          this.isSaveing = false
          if (res.code == 200) {
            this.closeSelectedTag(this.$route)
            this.$router.push({
              path: '/goods/purchaseManagement'
            })
            this.$message.success("操作成功")
          }
        }
      })
    },

    cencel () {
      this.closeSelectedTag(this.$route)
      this.$router.push({
        path: '/goods/purchaseManagement'
      })
    },
    //关闭tag
    closeSelectedTag (tag) {
      this.$store.commit("removeViewTags", tag)
      this.$store.commit("removeIframeList", tag)
      this.$store.commit("removeKeepLive", tag.name)
    },

  }
}
</script>
<style lang="scss" scoped>
.box {
  margin: 10px;
}
.el-form {
  // width: 100%;
  padding: 30px;
  background: #fff;
}

.button {
  margin-top: 50px;
}

.pass {
  :deep(.el-radio__input.is-checked + .el-radio__label) {
    color: #409eff !important;
  }

  :deep(.el-radio__input.is-checked) {
    .el-radio__inner {
      background: #409eff !important;
      border-color: #409eff !important;
    }
  }
}

.refuse {
  :deep(.el-radio__input.is-checked + .el-radio__label) {
    color: #f56c6c !important;
  }

  :deep(.el-radio__input.is-checked) {
    .el-radio__inner {
      background: #f56c6c !important;
      border-color: #f56c6c !important;
    }
  }
}
</style>